package com.blb.thread;

import java.util.ArrayList;
import java.util.List;

/**
 * 包子铺
 */
public class BaoziShop {

    //临界值
    public static final int MAX_COUNT = 100;
    //缓冲区
    private List<Baozi> baozis = new ArrayList<>();

    /**
     * 做包子
     */
    public synchronized void makeBaozi(){
        //判断缓冲区是否满了
        if(baozis.size() >= MAX_COUNT){
            System.out.println("包子铺满了，师傅等待 " + Thread.currentThread().getName());
            try {
                //满了，生产者等待
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }else{
            //没有满，通知消费者来买
            this.notifyAll();
        }
        //做包子放缓冲区
        Baozi baozi = new Baozi(baozis.size());
        baozis.add(baozi);
        System.out.println("师傅" + Thread.currentThread().getName() + "做了" + baozi);
    }

    /**
     * 卖包子
     */
    public synchronized void sellBaozi(){
        //判断缓冲区是否空了
        if(baozis.size() == 0){
            System.out.println("包子铺空了，消费者等待 " + Thread.currentThread().getName());
            try {
                //空了，消费者等待
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }else{
            //没有空，通知师傅来做
            this.notifyAll();
        }
        //从缓冲区拿包子，卖给消费者
        if(baozis.size() > 0){
            Baozi baozi = baozis.remove(0);
            System.out.println("消费者" + Thread.currentThread().getName() + "吃了" + baozi);
        }
    }
}
